package cn.hengzhu.main_manager.web.controller;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.hengzhu.main_manager.utils.SecurityUtil;
import cn.hengzhu.main_manager.utils.XmlPullUtil;


@Controller
@RequestMapping("/jump")
public class JumpController {

	@RequestMapping(method = RequestMethod.GET)
	public void getJumpAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 加密认证
		// 1)获取携带四个参数
		// signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
		String signature = request.getParameter("signature");
		// timestamp 时间戳
		String timestamp = request.getParameter("timestamp");
		// nonce 随机数
		String nonce = request.getParameter("nonce");
		// echostr 随机字符串
		String echostr = request.getParameter("echostr");
		// 2)使用这四个参数,安装微信规定完成加密认证
		// 1）将token、timestamp、nonce三个参数进行字典(数组)序排序
		String[] params = { "open", timestamp, nonce };
		Arrays.sort(params);
		// 2）将三个参数字符串拼接成一个字符串进行sha1加密
		StringBuilder sb = new StringBuilder();
		for (String param : params) {
			sb.append(param);
		}
		String content = sb.toString();
		String securityContent = SecurityUtil.sha1(content);
		// 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		if (signature.equals(securityContent)) {
			// 认证成功
			response.getWriter().println(echostr);
		} else {
			// 认证失败
			throw new RuntimeException("认证失败!");
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public void jump(HttpServletRequest request, HttpServletResponse response) throws Exception {
		 
		 
		  //2 使用xmlpull解析请求内容
		  //字节流
		  ServletInputStream inputStream = request.getInputStream();
		  //转换为字符流
		  InputStreamReader isReader  = new InputStreamReader(inputStream, "utf-8");
		  Map<String, String> result = XmlPullUtil.parse(isReader);
		  printMap(result);
	}
	
	
	public  void printMap(Map<String, String> result) {
		Set<Entry<String, String>> entrySet = result.entrySet();
		Iterator<Entry<String, String>> iterator = entrySet.iterator();
		while (iterator.hasNext()) {
			Entry<String, String> next = iterator.next();
			System.out.println(next);
		}

	}
}












